package com.zhsj.OkeHomeConsumption.ui.fragment;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.orhanobut.hawk.Hawk;
import com.zhsj.OkeHomeConsumption.R;
import com.zhsj.OkeHomeConsumption.common.Constants;
import com.zhsj.OkeHomeConsumption.common.OkeHomeConsumptionApi;
import com.zhsj.OkeHomeConsumption.empty.CliengExpadSharedBean;
import com.zhsj.OkeHomeConsumption.empty.CliengSharedBean;
import com.zhsj.OkeHomeConsumption.empty.FormalUserInfo;
import com.zhsj.OkeHomeConsumption.network.HttpClient;
import com.zhsj.OkeHomeConsumption.network.JsonResponseHandler;
import com.zhsj.OkeHomeConsumption.other.TimeChecker;
import com.zhsj.OkeHomeConsumption.other.URLEntity;
import com.zhsj.OkeHomeConsumption.ui.activity.wallet.BaseFragment;
import com.zhsj.OkeHomeConsumption.ui.activity.wallet.ProgressDrawableAlertDialog;
import com.zhsj.OkeHomeConsumption.ui.activity.wallet.TimeOutHandler;
import com.zhsj.OkeHomeConsumption.utils.LogUtils;
import com.zhsj.OkeHomeConsumption.utils.SharedPreferanceUtils;
import com.zhsj.OkeHomeConsumption.utils.SignUtil;

import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import static com.zhsj.OkeHomeConsumption.common.Constants.SHARED_PERFERENCE_USERINFO;


/**
 * <p>文件描述：邀请客户<p>
 * <p>作者：xingdx<p>
 * <p>创建时间：2018/11/13<p>
 * <p>更改时间：2018/11/13<p>
 */
public class CliengSharedView extends BaseFragment implements View.OnClickListener {
    // 左标题
    private TextView topbar_textview_leftitle = null;
    // 主标题
    private TextView topbar_textview_title = null;
    // 右标题
    private TextView topbar_textview_righttitle = null;

    /**
     * 计时器
     */
    private TimeChecker timeChecker = null;
    /**
     * 实例化ProgressDrawableAlertDialog
     */
    private ProgressDrawableAlertDialog pDialogUtils = null;

    private ArrayList<CliengExpadSharedBean> CliengSharedlist = null;
    private List<List<CliengSharedBean>> child = new ArrayList<List<CliengSharedBean>>();
    private List<String> listgrour = null;
    private ExpandableListView clieng_expadlist;
    private ExpandableAdapter adapter;
    private RecyclerView recyleview_clieng;
    private FormalUserInfo userInfo;
    private int posion = -1;
    private int type = 0;
    //顶部Tab
    private TabLayout mTab;
    private List<String> title_list = null;

    private SharedPreferanceUtils shared = null;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    public static CliengSharedView newInstance() {

        Bundle args = new Bundle();
        CliengSharedView fragment = new CliengSharedView();
        fragment.setArguments(args);
        return fragment;
    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_clientshared, container, false);
        initView(view);
        initdata();
        return view;
    }

    private void initView(View view) {
        shared = new SharedPreferanceUtils(getActivity());
        userInfo = Hawk.get(Constants.SHARED_PERFERENCE_USERINFO);;
        topbar_textview_leftitle = (TextView) view.findViewById(R.id.topbar_textview_leftitle);
        topbar_textview_leftitle.setVisibility(View.VISIBLE);
        topbar_textview_leftitle.setOnClickListener(this);
        topbar_textview_title = (TextView) view.findViewById(R.id.topbar_textview_title);
        topbar_textview_title.setText("邀请客户");
        topbar_textview_righttitle = view.findViewById(R.id.topbar_textview_righttitle);
        recyleview_clieng = view.findViewById(R.id.clieng_list);
        recyleview_clieng.setVisibility(View.GONE);
        clieng_expadlist = view.findViewById(R.id.clieng_expadlist);
        clieng_expadlist.setVisibility(View.VISIBLE);
        mTab = (TabLayout) view.findViewById(R.id.tab);
        title_list = new ArrayList<String>();
    }

    private void initdata() {
        title_list.add("分享");
        title_list.add("邀请");
        for (int i = 0; i < title_list.size(); i++) {
            mTab.addTab(mTab.newTab().setText(title_list.get(i)));
        }
        listgrour = new ArrayList<>();
        timeChecker = new TimeChecker(TimeOutHandler.timeOutHandler, Constants.TIME_OUT);
        pDialogUtils = new ProgressDrawableAlertDialog(getActivity());
        adapter = new ExpandableAdapter();
        clieng_expadlist.setGroupIndicator(null);//设置自带的箭头消失
        clieng_expadlist.setDivider(null);//设置没有分割线
        SharedListPost(0);
        mTab.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                if (tab.getPosition() == 0) {
                    SharedListPost(0);
                } else if (tab.getPosition() == 1) {
                    SharedListPost(5);
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
        clieng_expadlist.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {

            @Override
            public boolean onChildClick(ExpandableListView parent, View v,
                                        int groupPosition, int childPosition, long id) {
                start(SharedWebview.newInstance((CliengSharedBean) adapter.getChild(groupPosition, childPosition), userInfo, 0));
                return false;
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.topbar_textview_leftitle:
                _mActivity.onBackPressed();
                break;
        }
    }
    /*
     *  获取分享列表
     */
    public void SharedListPost(int type) {
        // TODO Auto-generated method stub
        // post传参使用的HashMap
        HashMap<String, String> paramMaps = new HashMap<String, String>();
        // 生成sign值所使用的HashMap
        final HashMap<String, String> mLogOnHashMap = new HashMap<String, String>();
        mLogOnHashMap.put("v", Constants.APPVERSION);
        mLogOnHashMap.put("t", Constants.TIME);
        mLogOnHashMap.put("deviceId", URLEntity.getInstance().getImei());
        mLogOnHashMap.put("platform", Constants.PLAFORM);
        mLogOnHashMap.put("deviceToken", Constants.DEVICETOKEN);
        mLogOnHashMap.put("client", Constants.CLIENT);
        mLogOnHashMap.put("partnerType", type + "");
        mLogOnHashMap.put("pagesize", "20");
        mLogOnHashMap.put("page", "0");
        paramMaps.put("partnerType", type + "");
        paramMaps.put("pagesize", "20");
        paramMaps.put("page", "0");
        // 网络计时器及线程
        TimeOutHandler.pDialogUtils = pDialogUtils;
        pDialogUtils.show();
        timeChecker.start();
        // 获取sign签名
        Constants.SIGN = SignUtil.getInstance().getSign(mLogOnHashMap);
        HttpClient.post(OkeHomeConsumptionApi.ELVDOU_SHARING, paramMaps, new JsonResponseHandler() {

            @Override
            public void onSuccess(int statusCode, String content) {
                // TODO Auto-generated method stub
                super.onSuccess(statusCode, content);
                timeChecker.check();
                pDialogUtils.dismiss();
                TimeOutHandler.pDialogUtils = null;
                LogUtils.e("content_anli", content);
                try {
                    JSONTokener jsonT = new JSONTokener(content);
                    JSONObject jsonOBJ = (JSONObject) jsonT.nextValue();
                    String code = jsonOBJ.optString("code");
                    String message = jsonOBJ.optString("message");
                    Boolean success = jsonOBJ.optBoolean("success");
                    if (success) {
                        if (CliengSharedlist != null) {
                            CliengSharedlist.clear();
                            listgrour.clear();
                            child.clear();
                        }
                        JSONArray datajsonArray = jsonOBJ.optJSONArray("data");
                        CliengSharedlist = new Gson().fromJson(datajsonArray.toString(), new
                                TypeToken<ArrayList<CliengExpadSharedBean>>() {
                                }.getType());
                        for (int i = 0; i < CliengSharedlist.size(); i++) {
                            listgrour.add(CliengSharedlist.get(i).getName());
                            child.add(CliengSharedlist.get(i).getChildren());
                        }
                        clieng_expadlist.setAdapter(adapter);
                    } else if (code.equals(Constants.STATUSTOKENERROR)) {
                        // token过期
                    } else {
                        if (!message.equals("null")) {
                            showShortToast(message);
                        }

                    }
                } catch (Exception ex) {
                    LogUtils.e("SchemListPost", "数据获取异常 ");
                }
            }

            @Override
            public void onFailure(Throwable e) {
                // TODO Auto-generated method stub
                super.onFailure(e);
                timeChecker.check();
                pDialogUtils.dismiss();
                TimeOutHandler.pDialogUtils = null;
                LogUtils.e("onFailure", "" + e.toString());
            }
        });
    }

    class ExpandableAdapter extends BaseExpandableListAdapter {

        @Override
        public int getGroupCount() {
            return listgrour.size();//获取父布局个数
        }

        @Override
        public int getChildrenCount(int groupPosition) {
            return child.get(groupPosition).size();//获取子布局个数
        }

        @Override
        public Object getGroup(int groupPosition) {
            return listgrour.get(groupPosition);
        }

        @Override
        public Object getChild(int groupPosition, int childPosition) {
            return child.get(groupPosition).get(childPosition);
        }

        @Override
        public long getGroupId(int groupPosition) {
            return groupPosition;
        }

        @Override
        public long getChildId(int groupPosition, int childPosition) {
            return childPosition;
        }

        @Override
        public boolean hasStableIds() {
            return true;
        }

        //父布局样式
        @Override
        public View getGroupView(int groupPosition, boolean isExpanded,
                                 View convertView, ViewGroup parent) {
            if (convertView == null) {
                LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                convertView = inflater.inflate(R.layout.item_cliengsharen_item, null);
            }
            TextView tvparent = (TextView) convertView.findViewById(R.id.title_text);
            tvparent.setText(getGroup(groupPosition).toString());
            ImageView ivView = (ImageView) convertView.findViewById(R.id.jiantou_img);
            if (isExpanded) {
                ivView.setBackgroundResource(R.mipmap.qianbao_xia);
            } else {
                ivView.setBackgroundResource(R.mipmap.qianbao_shang);
            }
            return convertView;
        }

        //子布局样式
        @Override
        public View getChildView(int groupPosition, int childPosition,
                                 boolean isLastChild, View convertView, ViewGroup parent) {
            if (convertView == null) {
                LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                convertView = inflater.inflate(R.layout.item_cliengsharen, null);
            }
            ImageView newpro_im_des = (ImageView) convertView.findViewById(R.id.icon_img);
            Glide.with(getActivity()).load(child.get(groupPosition).get(childPosition).getImagePath()).placeholder(R.drawable.zhanweitu_bg).into(newpro_im_des);
//            ImageLoader.getInstance().displayImage(child.get(groupPosition).get(childPosition).getImagePath(), newpro_im_des);
            TextView tvchild = (TextView) convertView.findViewById(R.id.title_text);
            tvchild.setText(child.get(groupPosition).get(childPosition).getTitle());
            return convertView;
        }

        @Override
        public boolean isChildSelectable(int groupPosition, int childPosition) {
            return true;
        }

    }

}
